<template>
    <div>
        <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="用户名" prop="username">
                <el-input v-model.number="ruleForm.username" @keyup.enter.native="submitForm('ruleForm')"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input type="password" v-model="ruleForm.password" autocomplete="off" @keyup.enter.native="submitForm('ruleForm')"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary"  @click="submitForm('ruleForm')">提交</el-button>
                <el-button @click="resetForm('ruleForm')">重置</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import nuxtStorage from 'nuxt-storage';

export default {
    name: "Login",
    data() {
        return {
            ruleForm: {
                password: '',
                username: ''
            },
            rules: {
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                ],

                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                ]
            }
        };
    },
    methods: {
        submitForm(formName) {

            let api = "/api/login"
            let that = this
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.$axios.post(api, that.ruleForm).then((response) => {
                        let code = response.data.code

                        if (code == 0) {
                            let data = response.data.data
                            nuxtStorage.localStorage.setData("user", JSON.stringify(data.user))
                            nuxtStorage.localStorage.setData("nick_name", data.user.nick_name)
                            nuxtStorage.localStorage.setData("access_token", data.access_token)
                         
                            this.$message({
                                message: '登录成功',
                                type: 'success'
                            });

                            this.$router.push({ path: '/admin/content/'}).catch(() => { })
                        }
                    })
                }
            });



        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        }
    }
}
</script>